var express=require("express");
var router=express.Router();
var User=require("../model/user");
var util=require("../common/util");
//注册模块
router.get("/register",function(req,res,next){
	res.render("register");
});
router.post("/register",function(req,res,next){
	var username=req.body.username;
	var password=req.body.password;
	var erpassword=req.body.erpassword;
	var age=req.body.age;
	var phone=req.body.phone;
	var nickname=req.body.nickname;
    User.find({ "phone": phone }, function (err, docs) {
        console.log(docs);
        if (docs.length > 0) {
            res.send({ "status": 1, "msg": "phone has register" });
            res.end();
            return;
        }
        else {
            User.find({ "username": username }, function (err, docs) {
                if (docs.length > 0) {
                    res.send({ "status": 1, "msg": "username has register" });
                    res.end();
                    return;
                    }
                var pwd = util.md5(password);
                var user = new User({
                    username: username,
                    password: pwd,
                    phone: phone,
                    nickname: nickname,
                    age: age
                });
                user.save(function (err, data) { console.log(err) });
                res.send({ "status": 0, "msg": "success" });

            });
        }
    });
   
   
})

//登陆模块
router.get("/login",function(req,res,next)
{
	res.render('login');
});
router.post("/login", function (req, res, next) {
    var email = req.body.email;
    var pwd = req.body.pwd;
    if (util.isNull(email) || util.isNull(pwd)) {
        res.send({ "status": 1, "msg": "不能为空" });
    }
     User.findOne({"username":email},function(err,user){
       if(user!=null)
       {
           if(user.password===util.md5(pwd))
           {
               console.log(user.username);
               req.session.userid=user.username;
               res.send({"status":0,"msg":"success"});
               res.end();
               return;
           }
            res.send({"status":1,"msg":"Password is error"});
            res.end();
            return;
       }
       res.send({"status":1,"msg":"用户名不存在"});
       res.end();
   });
});
module.exports=router;